package cn.fl.settlement.controller;

import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.logger.eum.LogExceptionEnum;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.EncryptUtil;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.customer.service.ICstBankService;
import cn.fl.customer.vo.CstBankVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.project.constant.PrjPrdPaySchBankConstant;
import cn.fl.project.constant.PrjQuatPrpsConstant;
import cn.fl.project.service.IPrjPrdPaySchBankService;
import cn.fl.project.vo.PrjPrdPaySchBankVO;
import cn.fl.system.constant.SysLogConstant;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import fl.customer.facade.customer.condition.CstBankQueryCondition;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
* @Description:    结清客户银行账户Controller
* @Author:         liurong
* @CreateDate:     2020/3/23 11:46
* @Version:        1.0
*/
@Controller
@RequestMapping("/settle/bank")
public class SettleCstBankController extends BaseController {

    @Autowired
    private ICstBankService cstBankService;

    @Autowired
    private IPrjPrdPaySchBankService prjPrdPaySchBankService;

    /**
     * 跳转到选择退款银行账户列表页面
     * @param request
     * @return
     */
    @RequestMapping(value = "/toChooseBank.do", method = {RequestMethod.GET})
    public ModelAndView toChooseBank(HttpServletRequest request) {
        String cstId = request.getParameter("cstId");
        String paySchId = request.getParameter("paySchId");

        ModelAndView mav = new ModelAndView("project/settleOfFinaInst/chooseRefundBank");
        mav.addObject("cstId", cstId);
        mav.addObject("paySchId", paySchId);
        return mav;
    }

    /**
     * 加载客户银行账户信息
     * @param request
     * @return
     */
    @RequestMapping(value = "/loadCstBankData.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object loadCstBankData(HttpServletRequest request) throws BaseException {
        try {
            String currentPage = request.getParameter("page");
            String pageSize = request.getParameter("pagesize");
            String cstId = request.getParameter("cstId");

            if (StringUtils.isEmpty(cstId)) {
                return new ListPageVO<>(new ArrayList<CstBankVO>(), 0);
            }
            Pager page = new Pager();
            page.setCurrentPage(StringUtils.isNotEmpty(currentPage) ? Integer.parseInt(currentPage) : 1);
            page.setEveryPage(StringUtils.isNotEmpty(pageSize) ? Integer.parseInt(pageSize) : 10);

            CstBankQueryCondition condition = new CstBankQueryCondition();
            List<Long> cstIds = Lists.newArrayList();
            cstIds.add(Long.valueOf(cstId));
            condition.setCstIdList(cstIds);
            condition.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
            condition.setSysCd(CurrentThreadContext.getCurrentSysCd());
            page.setCondition(condition);
            Pager pager = cstBankService.searchListPage(page);
            List<CstBankVO> list = (List<CstBankVO>) pager.getResultList();

            List<CstBankVO> resultList = null;
            if (CollectionUtils.isNotEmpty(list)) {
                resultList = Lists.newArrayListWithCapacity(list.size());
                for (CstBankVO vo : list) {
                    CstBankVO resultVo = new CstBankVO();
                    resultVo.setId(vo.getId());
                    resultVo.setAccNo(EncryptUtil.cardNoEncrypt(vo.getAccNo()));
                    resultVo.setCertNo(EncryptUtil.certNoEncrypt(vo.getCertNo()));
                    resultVo.setBkCdNm(vo.getBkCdNm());
                    resultVo.setAccOrgNm(vo.getAccOrgNm());
                    resultVo.setAccNm(vo.getAccNm());
                    resultVo.setAccTypCdNm(vo.getAccTypCdNm());
                    resultVo.setCertTypCdNm(vo.getCertTypCdNm());
                    resultVo.setBkNo(vo.getBkNo());
                    resultList.add(resultVo);
                }
            }
            ListPageVO<CstBankVO> listPage = new ListPageVO<>(resultList, pager.getTotalCount());
            return listPage;
        } catch (Exception e) {
            BaseLogUtils.newLogger("加载客户银行账户信息失败！").setThrowable(e).error(LogExceptionEnum.API_CODE_0102);
            throw e;
        }
    }

    /**
     * 选择并确认客户退款账户
     * @param request
     * @return
     * @throws BaseException
     */
    @RequestMapping(value = "/confirmRefundBank.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object confirmRefundBank(HttpServletRequest request) throws BaseException {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
        String paySchId = request.getParameter("paySchId");
        String bId = request.getParameter("bId");
        try {
            PrjPrdPaySchBankVO bankVO = new PrjPrdPaySchBankVO();
            bankVO.setCstBankId(Long.parseLong(bId));
            bankVO.setPaySchId(Long.parseLong(paySchId));
            bankVO.setFundFlowCd(PrjQuatPrpsConstant.CODE_PRJ_QUAT_CASH_FLOW_OUT);//资金流出
            bankVO.setFundTypCd(PrjPrdPaySchBankConstant.CODE_PAY_SCH_FUND_TYP_CD_INTO);//收款账户
            bankVO.setCrtTm(new Date());
            bankVO.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
            bankVO.setMdfTm(new Date());
            bankVO.setMdfUsrId(CurrentThreadContext.getCurrentUserId());

            List<PrjPrdPaySchBankVO> list = Lists.newArrayList();
            list.add(bankVO);
            boolean success = prjPrdPaySchBankService.batchAdd(list);
            if (!success) {
                throw new BaseException("选择并确认客户退款账户失败！");
            }
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_OPERATE_FAIL + ex.getMessage());
            BaseLogUtils.newLogger("选择并确认客户退款账户业务异常！" + paySchId).setKeys("confirmRefundBank", CurrentThreadContext.getCurrentUserName()).setThrowable(ex).error(LogExceptionEnum.API_CODE_0102);
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
            BaseLogUtils.newLogger("选择并确认客户退款账户系统异常！" + paySchId).setKeys("confirmRefundBank", CurrentThreadContext.getCurrentUserName()).setThrowable(ex).error(LogExceptionEnum.API_CODE_0102);
        }
        return result;
    }

    /**
     * 确认结清账户（我司付款账户）
     * @param request
     * @return
     * @throws BaseException
     */
    @RequestMapping(value = "/confirmStlBankInfo.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object confirmOurComPay(HttpServletRequest request) throws BaseException {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
        String paySchId = request.getParameter("paySchId");
        String fundFlowCd = request.getParameter("fundFlowCd");
        String fundTypCd = request.getParameter("fundTypCd");
        try {
            if (StringUtils.isEmpty(paySchId) || StringUtils.isEmpty(fundFlowCd) || StringUtils.isEmpty(fundTypCd)) {
                throw new BaseException("请求参数不能为空！");
            }
            boolean bol = prjPrdPaySchBankService.modifyConfirmMark(Long.parseLong(paySchId), fundFlowCd, fundTypCd);
            if (!bol) {
                throw new BaseException("确认失败！");
            }
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_OPERATE_FAIL + ex.getMessage());
            BaseLogUtils.newLogger("确认结清账户信息业务异常！" + paySchId).setKeys("confirmOurComPay", CurrentThreadContext.getCurrentUserName()).setThrowable(ex).error(LogExceptionEnum.API_CODE_0102);
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
            BaseLogUtils.newLogger("确认结清账户信息系统异常！" + paySchId).setKeys("confirmOurComPay", CurrentThreadContext.getCurrentUserName()).setThrowable(ex).error(LogExceptionEnum.API_CODE_0102);
        }
        return result;
    }


}

